﻿using Flurl.Http;
using Flurl.Http.Configuration;
using Microsoft.AspNetCore.Components.Authorization;
using MXERP.Infrastructure.Authentication;
using MXERP.Shared.Constants;
using MXERP.Shared.Wrapper;

namespace MXERP.Infrastructure.Managers
{
    public class SignEntryManager : ISignEntryManager
    {
        private readonly IFlurlClient _flurlClient;
        private readonly ILocalStorageService _localStorageService;
        private readonly AuthenticationStateProvider _authenticationStateProvider;
        public SignEntryManager(IFlurlClientCache clients, ILocalStorageService localStorageService, AuthenticationStateProvider authenticationStateProvider)
        {
            _flurlClient = clients.Get(ApiConstant.MXERP);
            _localStorageService = localStorageService;
            _authenticationStateProvider = authenticationStateProvider;
        }
        public async Task<ApiResponse<SignInResponse>> SignIn(SignInRequest request)
        {
            var result = await _flurlClient.Request(EndpointConstant.SignEnTry.SignIn).PostJsonAsync(request).ReceiveJson<ApiResponse<SignInResponse>>();
            await _localStorageService.SetItemAsync(StorageConstant.Local.AuthToken, result.Data.Token);
            await _localStorageService.SetItemAsync(StorageConstant.Local.RefreshToken, result.Data.RefreshToken);
            await ((CustomStateProvider)_authenticationStateProvider).StateChangedAsync();
            return result;
        }
        public async Task SignOut()
        {
           await _flurlClient.Request(EndpointConstant.SignEnTry.SignOut).GetAsync();
        }
        public async Task<ApiResponse<SignInResponse>> RefreshToken()
        {
            var refreshToken = await _localStorageService.GetItemAsync<string>(StorageConstant.Local.RefreshToken);
            var result = await _flurlClient.Request(EndpointConstant.SignEnTry.RefreshToken).PostJsonAsync(new RefreshTokenRequest { RefreshToken = refreshToken }).ReceiveJson<ApiResponse<SignInResponse>>();
            await _localStorageService.SetItemAsync(StorageConstant.Local.AuthToken, result.Data.Token);
            await _localStorageService.SetItemAsync(StorageConstant.Local.RefreshToken, result.Data.RefreshToken);
            await ((CustomStateProvider)_authenticationStateProvider).StateChangedAsync();
            return result;
        }
    }
}
